import { CommonModule } from "@angular/common";
import {
  NgModule,
  ModuleWithProviders,
  APP_INITIALIZER,
  LOCALE_ID,
  Injectable,
  PLATFORM_ID,
  APP_ID,
  Inject
} from "@angular/core";

import { isPlatformBrowser, isPlatformServer } from "@angular/common";

// l10n
import {
  L10nConfig,
  L10nLoader,
  LocalizationModule,
  LocaleValidationModule,
  StorageStrategy,
  ProviderType,
  ISOCode,
  TranslationConfig,
  TRANSLATION_CONFIG
} from "angular-l10n";

export const l10nConfig: L10nConfig = {
  locale: {
    languages: [
      { code: "en", dir: "ltr" },
      { code: "de", dir: "ltr" },
      { code: "zh", dir: "ltr" }
    ],
    defaultLocale: {
      languageCode: "en",
      countryCode: "US",
      numberingSystem: "latn"
    },
    currency: "USD",
    storage: StorageStrategy.Cookie,
    cookieExpiration: 30,
    localizedRouting: [ISOCode.Language, ISOCode.Country]
  },
  translation: {
    caching: true,
    version: "6.3.0",
    composedKeySeparator: ".",
    missingValue: "No key",
    i18nPlural: true
  }
};

@Injectable({
  providedIn: "root"
})
export class LocalizationConfig {
  constructor(
    public l10nLoader: L10nLoader,
    @Inject(TRANSLATION_CONFIG) private translationConfig: TranslationConfig,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {}

  load(): Promise<void> {
    if (isPlatformBrowser(this.platformId)) {
      // Client only code.
      this.translationConfig.providers = [
        { type: ProviderType.Static, prefix: "/assets/l10n/locale-" }
      ];
    }
    if (isPlatformServer(this.platformId)) {
      // Server only code.
      this.translationConfig.providers = [
        {
          type: ProviderType.Static,
          prefix: "/assets/l10n/locale-"
        }
      ];
    }

    return this.l10nLoader.load();
  }
}

export function initLocalization(
  localizationConfig: LocalizationConfig
): Function {
  return () => localizationConfig.load();
}

@NgModule({
  declarations: [],
  imports: [CommonModule, LocalizationModule],
  exports: [LocalizationModule],
  providers: []
})
export class L10nModule {}
